package com.hqyj.realm;

import com.hqyj.pojo.Role;
import com.hqyj.pojo.User;
import com.hqyj.service.RoleService;
import com.hqyj.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.Set;

/**
 * @author chen3
 * @description
 * @date 2021-08-12 11:04
 */
public class MyShiroRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("权限管理");
        //获取待授权的用户名
        String username = (String)principals.getPrimaryPrincipal();
        //系统中查询待授权用户的权限信息 ： 角色信息、权限信息
        User user = userService.getOneByUsername(username);
        //组装一个Set<String>型角色信息
        Set<String> roles = new HashSet<>();

        Role role = roleService.queryById(user.getRoleId());
        roles.add(role.getRoleName());

        //创建一个授权信息对象
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //赋予角色相关的授权信息
        info.setRoles(roles);

        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("用户认证");
        //使用认证令牌获取当前待登录的用户名
        String username = (String) token.getPrincipal();
        //在我们的系统中查询用户的认证信息
        User user = userService.getOneByUsername(username);
        //如果用户不存在，抛出用户不存在的异常
        if(user == null){
            throw new UnknownAccountException(username+"不存在");
        }
        //在shiro会话域中共享用户信息，以便业务层获取使用
        Session session = SecurityUtils.getSubject().getSession();
        session.setAttribute("loginUser",user);
        //提供暗文密码,使用四个参数的构造方法来构造，用户名、密码、暗文密码、当前认证域的名称
        ByteSource saltBytes = ByteSource.Util.bytes(user.getUsername());
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(username, user.getPassword(), saltBytes, getName());
        System.out.println("获取认证信息");
        return info;
    }
}
